<template>
  <uv-navbar :fixed="false" :title="title" left-arrow @leftClick="$onClickLeft" />
  <view style="overflow: hidden;background:#fff;">
    <view class="set-box bg-white">
      <uv-alert type="warning" v-if="form.checkStatus == 1" description="订单正在审核中,不可以修改!"></uv-alert>
      <uv-alert type="warning" v-else-if="form.checkStatus == 2" description="订单已经审核通过,不可以修改!"></uv-alert>
      <uv-alert type="warning" v-else-if="form.checkStatus == 3" description="审核不通过，不可修改数据，请重新添加订单!"></uv-alert>
      <uv-form :model="form" ref="uForm" :errorType="errorType" labelWidth="85" :rules="rules">
        <uv-form-item required label="订单编号:" prop="number">
          <uv-input v-model="form.number" :disabled="isCheck" />
        </uv-form-item>
        <uv-form-item required label="订单名称:" prop="name">
          <uv-input v-model="form.name" :disabled="isCheck" />
        </uv-form-item>
        <uv-form-item label="选择客户:" @click="type != 'check' ? selectShow() : ''" prop="customerName" required>
          <uv-input disabledColor="#ffffff" disabled v-model="form.customerName" placeholder="选择客户">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="选择商机:" @click="type != 'check' ? selectShow4() : ''">
          <uv-input disabledColor="#ffffff" disabled v-model="form.businessName" placeholder="选择商机">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="订单金额:" prop="money" required>
          <uv-input type="number" v-model="form.money" :disabled="true" />
        </uv-form-item>
        <uv-form-item label="下单时间 :" @click="type != 'check' ? createTimeShow() : ''">
          <uv-input v-model="orderTime" placeholder="选择下单时间 " disabled disabledColor="#ffffff">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="客户联系人:" @click="type != 'check' ? selectShow2() : ''" required>
          <uv-input disabledColor="#ffffff" disabled v-model="form.contactsIdName" placeholder="请选择客户后选择客户联系人">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="销售人员:" @click="type != 'check' ? selectShow3() : ''" required>
          <uv-input disabledColor="#ffffff" disabled v-model="form.orderAdminName" placeholder="选择销售人员">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="联系人地址:">
          <uv-input type="type" placeholder="请选择客户后自动获取客户联系人地址" v-model="detailAddress" :disabled="true" />
        </uv-form-item>
        <uv-form-item label="付款类型:" @click="type != 'check' ? selectShow5() : ''" required>
          <uv-input disabledColor="#ffffff" disabled v-model="form.payTypeName" placeholder="选择付款类型">
            <template v-slot:suffix>
              <uv-icon name="arrow-right"></uv-icon>
            </template>
          </uv-input>
        </uv-form-item>
        <uv-form-item label="财务备注:">
          <uv-textarea v-model="form.remark" :disabled="isCheck" placeholder="请输入财务备注"></uv-textarea>
        </uv-form-item>
        <uv-form-item label="物流备注:">
          <uv-textarea v-model="form.wmsRemark" :disabled="isCheck" placeholder="请输入物流备注"></uv-textarea>
        </uv-form-item>
        <uv-form-item label="业绩拆分:">
          <div class="flex flex-wrap">
            <uv-button @click="openPerFormance" type="primary" text="选择其他业务员"></uv-button>
            <uv-tags closable class="ml-1" :text="item.nickname" v-for="(item, inx) in addperformanceArray"
              :key="inx"></uv-tags>
          </div>
        </uv-form-item>
      </uv-form>
      <!-- 产品 -->
      <view class="flex cif-title" @click="selectProduct">
        <view class="flex-1 text">产品关联</view>
        <view class="flex align-center" style="color: #2979ff">
          选择产品<uv-icon name="arrow-right" color="#909399" size="20"></uv-icon>
        </view>
      </view>
      <view class="list">
        <block v-if="selectList.length > 0">
          <view class="item" v-for="(item, index) in selectList" :key="index">
            <view class="number flex">
              <view class="flex-1">序号: {{ index + 1 }} - {{ isCheck }}</view>
              <uv-number-box :min="1" v-model="item.nums" :longPress="false" @change="valChange()"></uv-number-box>
            </view>
            <view class="content flex align-center">
              <view class="flex-1 name">{{ item.storeName ? item.storeName : item.name }}({{ item.sku }})</view>
              <view class="price flex align-center">
                <view class="pr-1" style="font-weight: 600">￥</view>
                <uv-input type="number" :clearable="false" placeholder="请输入价格" v-model="item.price"
                  @input="inputChang()" />
              </view>
            </view>
            <view class="brief flex">
              <view class="">备注：</view>
              <uv-input v-model="item.remarks" :disabled="isCheck" />
            </view>
            <!-- 删除按钮 -->
            <view class="close" @click="type != 'check' ? remove(index) : ''">
              <uv-icon name="close" color="#909399" size="20"></uv-icon>
            </view>
          </view>
        </block>
        <uv-empty text="暂未选择产品" v-else margin-top="50" mode="list"></uv-empty>
      </view>
      <view class="flex mb-1 mt-1 align-center">
        <view class="mr-1" style="width: 150rpx">整单折扣%：</view>
        <view class="flex-1"><uv-input type="number" v-model="form.discountRate" :disabled="isCheck"
            placeholder="请填写0到100的数" @input="inputChang" /></view>
      </view>
      <view class="flex mb-1 mt-1 align-center">
        <view class="mr-1" style="width: 150rpx">总额：</view>
        <view class="flex-1"><uv-input type="number" v-model="form.totalPrice" :disabled="isCheck" /></view>
      </view>
      <uv-form-item label="审批流程" labelPosition="top" labelWidth="80">
        <flow-step :flowAdmins="flowAdmins" />
      </uv-form-item>
      <view class="mt-4 flex" style="text-align: center" v-if="!isCheck">
        <uv-button class="flex-fill mr-10" color="#09b4f1" @click="submit(1)"
          v-if="!form.status || form.status && form.status < 2" :ripple="true">暂存</uv-button>
        <uv-button class="flex-fill ml-10" color="#09b4f1" @click="submit(2)" :disabled="form.checkStatus == 1 || form.checkStatus == 2 || form.checkStatus == 3
          " :ripple="true">确定提交</uv-button>
      </view>
    </view>
    <!-- 选择客户弹窗 -->
    <uv-popup mode="bottom" round="38" ref="selectShowRef">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">选择客户</text>
          <view class="" @click="selectShowClose" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <uv-search margin="30rpx 20rpx" shape="square" v-model="keyword" :show-action="false" :clearabled="true"
          placeholder="输入客户名称搜索" @change="onSearch"></uv-search>
        <scroll-view scroll-y style="height: 760rpx; width: 100%" @scrolltolower="reachBottom">
          <view class="list">
            <block v-if="customerList.length > 0">
              <view class="mb-4">
                <view class="item flex" v-for="(item, index) in customerList" :key="index" @click="onItem(item, index)">
                  <view class="title">{{ item.name }}</view>
                  <view class="check-icon">
                    <uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
                  </view>
                </view>
              </view>
              <uv-load-more :status="listStatus"></uv-load-more>
            </block>
            <uv-empty text="暂无数据" v-else mode="list"></uv-empty>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <uv-popup mode="bottom" round="38" ref="selectShowRef2">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">选择客户签约人</text>
          <view class="" @click="selectShowClose2" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <scroll-view scroll-y style="height: 760rpx; width: 100%">
          <view class="list">
            <block v-if="customerContacts.length > 0">
              <view class="mb-4">
                <view class="item flex" v-for="(item, index) in customerContacts" :key="index"
                  @click="onItem2(item, index)">
                  <view class="title">{{ item.name }}</view>
                  <view class="check-icon">
                    <uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
                  </view>
                </view>
              </view>
            </block>
            <uv-empty text="暂无数据" v-else mode="list"></uv-empty>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <uv-popup mode="bottom" round="38" ref="selectShowRef3">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">选择公司签约人</text>
          <view class="" @click="selectShowClose3" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <uv-search margin="30rpx 20rpx" shape="square" v-model="keyword3" :show-action="false" :clearabled="true"
          placeholder="输入用户名称搜索" @change="onSearch3"></uv-search>
        <scroll-view scroll-y style="height: 760rpx; width: 100%" @scrolltolower="reachBottom3">
          <view class="list">
            <block v-if="userList.length > 0">
              <view class="mb-4">
                <view class="item flex" v-for="(item, index) in userList" :key="index" @click="onItem3(item, index)">
                  <view class="title">{{ item.nickname }}</view>
                  <view class="check-icon">
                    <uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
                  </view>
                </view>
              </view>
              <uv-load-more :status="listStatus3"></uv-load-more>
            </block>
            <uv-empty text="暂无数据" v-else mode="list"></uv-empty>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <uv-popup mode="bottom" round="38" ref="selectShowRef4">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">选择商机</text>
          <view class="" @click="selectShowClose4" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <scroll-view scroll-y style="height: 760rpx; width: 100%" @scrolltolower="reachBottom3">
          <view class="list">
            <block v-if="businessList.length > 0">
              <view class="mb-4">
                <view class="item flex" v-for="(item, index) in businessList" :key="index"
                  @click="onItem4(item, index)">
                  <view class="title">{{ item.name }}</view>
                  <view class="check-icon">
                    <uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
                  </view>
                </view>
              </view>
            </block>
            <uv-empty text="暂无数据" v-else mode="list"></uv-empty>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <uv-popup mode="bottom" round="38" ref="selectShowRef5">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">付款类型</text>
          <view class="" @click="selectShowClose5" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <scroll-view scroll-y style="height: 760rpx; width: 100%">
          <view class="list">
            <block v-if="typeList.length > 0">
              <view class="mb-4">
                <view class="item flex" v-for="(item, index) in typeList" :key="index" @click="onItem5(item, index)">
                  <view class="title">{{ item.label }}</view>
                  <view class="check-icon">
                    <uv-icon v-if="item.checked" name="checkmark" color="#09b4f1" size="28"></uv-icon>
                  </view>
                </view>
              </view>
              <uv-load-more :status="listStatus5"></uv-load-more>
            </block>
          </view>
        </scroll-view>
      </view>
    </uv-popup>
    <uv-popup mode="bottom" round="38" ref="performanceRef">
      <view class="popup-content">
        <view class="popup-title">
          <view class="" style="width: 45px"> </view>
          <text class="">选择业务员</text>
          <view class="" @click="performanceRefClose" style="width: 45px">
            <uv-icon name="close" color="#909399" size="30"></uv-icon>
          </view>
        </view>
        <template v-if="setp == 1">
          <view class="flex text-lg pl-2 pb-1 pt-1">选择其他业务员</view>
          <scroll-view scroll-y style="height: 60vh; width: 100%">
            <view class="list">
              <block v-if="userList.length > 0">
                <view class="mb-4">
                  <view class="item flex" v-for="(item, index) in userList" :key="index" @click="addPerformance(item)">
                    <view class="title">{{ item.nickname }}</view>
                    <view class="check-icon">
                      <uv-icon v-if="addperformanceRef.indexOf(item.id) > -1" name="checkmark" color="#09b4f1"
                        size="28"></uv-icon>
                    </view>
                  </view>
                </view>
              </block>
              <uv-empty text="暂无数据" v-else mode="list"></uv-empty>
            </view>
          </scroll-view>
          <view class="flex pl-2 pr-2 pt-1 pb-1">
            <uv-button class="flex-fill" @click="setpNext(2)" type="primary" text="下一步"></uv-button>
          </view>
        </template>
        <template v-else>
          <view class="flex text-lg pl-2 pb-1 pt-1">提示：所有人的比例加起来总数为100</view>
          <scroll-view scroll-y style="height: 60vh; width: 100%" class="pl-2 pr-2">
            <uv-form labelWidth="175">
              <uv-form-item :label="item.nickname" v-for="(item, inx) in addperformanceArray" :key="inx">
                <uv-input v-model="item.inputValue" placeholder="请输入分成比例（百分比%）"></uv-input>
              </uv-form-item>
            </uv-form>
          </scroll-view>
          <view class="flex pl-2 pr-2 pt-1 pb-1">
            <uv-button class="flex-fill" @click="setpNext(1)" type="primary" text="上一步"></uv-button>
            <div class="ml-1 mr-1"></div>
            <uv-button class="flex-fill" :disabled="flagButton()" @click="serveClosePerformance" type="primary"
              text="确定"></uv-button>
          </view>
        </template>
      </view>
    </uv-popup>
    <uv-datetime-picker ref="datetimePicker" v-model="timeValue" mode="datetime"
      @confirm="createTimeChange"></uv-datetime-picker>
    <uv-datetime-picker ref="datetimePicker2" v-model="timeValue2" mode="datetime"
      @confirm="createTimeChange2"></uv-datetime-picker>
    <uv-datetime-picker ref="datetimePicker3" v-model="timeValue2" mode="datetime"
      @confirm="createTimeChange3"></uv-datetime-picker>
  </view>
</template>

<script setup>
import { ref, unref, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { getCustomerListPage } from "@/api/customer";
import { getBusinessProductListByBusinessId, getBusinessPage } from "@/api/business";
import {
  getContractNo,
  createContract,
  getContract,
  getContractProductListByContractId,
  updateContract,
  getContactsList,
  check,
  setSplits
} from "@/api/contract";
import { getSimpleUserList, getFlowUsers, getSimpleUserList2 } from "@/api/user";
import { getDictTypeDate } from "@/api/index.js";
import AddressSelect from "@/components/AddressSelect/index.vue";
import { formatDateTime, prePage, formatTime } from "@/utils/util";
import { useMainStore } from "@/store/store";
import { storeToRefs } from "pinia";
const main = useMainStore();
const { selectProductList } = storeToRefs(main);
const title = ref("添加订单");
const typeList = ref([]);

const labelPosition = ref("left");
const keyword = ref("");
const listStatus = ref("loadmore");
const listStatus3 = ref("loadmore");
const listStatus5 = ref("loadmore");
const customerList = ref([]);
const goodsName = ref("");
const page = ref(1);
const page3 = ref(1);
const pageSize = ref(10);
const lastPage = ref(false);
const lastPage3 = ref(false);
const selectList = ref([]);
const checkUserList = ref({}); // 拆分的销售人员列表
const type = ref("add");
const contractId = ref(0);
const customerId = ref(0);
const nextTime = ref("");
const orderTime = ref(formatDateTime(new Date()));
const startTime = ref(formatDateTime(new Date()));
const endTime = ref(formatDateTime(new Date()));
const content = ref("");
const customerName = ref("");
const detailAddress = ref("");
const payTypeIndex = ref(0);
const form = ref({
  customerId: "",
  customerName: "",
  name: "",
  nextTime: "",
  startTime: new Date().getTime(),
  orderTime: new Date().getTime(),
  endTime: new Date().getTime(),
  money: "",
  remark: "",
  discountRate: 0,
  totalPrice: "",
  orderAdminName: "",
  payType: "",
  contactsId: "",
  contactsIdName: "",
  status: 1
});
const timeText = ref("");
const errorType = ref("message");
const rules = ref({});
const customerContacts = ref([]);
const userList = ref([]);
const nickname = ref("");
const keyword3 = ref("");
const businessList = ref([]);
const isCheck = ref(false);
const form2 = ref({
  id: 0,
  agreeType: 1,
  remark: "",
});
const flowAdmins = ref([]);

import cookie from "@/utils/cookie";
onLoad(async (e) => {
  await getUserList();
  await getdataliType(); // 获取字典
  if (e.type) {
    type.value = e.type;
  }
  if (type.value == "check") {
    isCheck.value = true;
    title.value = "订单详情";
    contractId.value = e.id;
    getContractInfo();
  } else if (type.value == "edit") {
    title.value = "编辑订单";
    contractId.value = e.id;
    getContractInfo();
  } else {
    getNumber();
    selectList.value = [];
    form.value.orderAdminId = cookie.get("userInfo").userId;
    let item = userList.value.filter((v) => {
      return v.id == form.value.orderAdminId;
    });
    if (item.length > 0) {
      form.value.orderAdminName = item.length > 0 ? item[0].nickname : '';
      item[0].inputValue = 50
      addperformanceRef.value.push(item[0].id);
      addperformanceArray.value.push(item[0]);
    }
    console.log(addperformanceArray.value, "数据");
  }

  getCustomerList();
  getFlowUsersList();
});
const getdataliType = async () => {
  const res = await getDictTypeDate({
    dictType: "payment_type",
    pageNo: 1,
    pageSize: 20,
  });
  typeList.value = res.list.map((v) => {
    return { ...v, checked: false };
  });
};

onShow(() => {
  selectList.value = selectProductList.value;
  count_price();
});

const getFlowUsersList = async () => {
  flowAdmins.value = await getFlowUsers({ flowType: "contract", id: contractId.value });
  let flowAdminsId = "";
  flowAdmins.value.forEach((item) => {
    if (flowAdminsId == "") {
      flowAdminsId = item.adminIds;
    } else {
      flowAdminsId = flowAdminsId + "," + item.adminIds;
    }
  });

  form.value.flowAdminId = flowAdminsId;
};

const getNumber = async () => {
  form.value.number = await getContractNo();
};

const selectShowRef = ref();
const selectShow = () => {
  unref(selectShowRef).open();
};
const selectShowClose = () => {
  unref(selectShowRef).close();
};

const datetimePicker = ref();
const createTimeShow = () => {
  unref(datetimePicker).open();
};

// 选择时间
const createTimeChange = (e) => {
  form.value.orderTime = e.value;
  console.log("form.value.orderTime:", form.value.orderTime);
  orderTime.value = formatDateTime(e.value);
};

const datetimePicker2 = ref();
const createTimeShow2 = () => {
  unref(datetimePicker2).open();
};

// 选择时间
const createTimeChange2 = (e) => {
  form.value.startTime = e.value;
  startTime.value = formatDateTime(e.value);
};

const datetimePicker3 = ref();
const createTimeShow3 = () => {
  unref(datetimePicker3).open();
};

// 选择时间
const createTimeChange3 = (e) => {
  form.value.endTime = e.value;
  endTime.value = formatDateTime(e.value);
};
// 获取详情-数据
const getContractInfo = async () => {
  console.log("1-1");
  form.value = await getContract({ id: contractId.value });
  //选择了客户 返回客户联系人
  let data = await getContactsList({ customerId: form.value.customerId });
  customerContacts.value = data.map((v) => {
    return { ...v, checked: false };
  });
  if (data.length > 0) {
    form.value.contactsIdName = data[0].name;
    form.value.contactsId = data[0].id;
    customerContacts.value[0].checked = true;
  }
  detailAddress.value = data.length > 0 ? data[0].detailAddress : "";
  typeList.value.forEach((item, index) => {
    if (item.value == form.value.payType) {
      item.checked = true;
    } else {
      item.checked = false;
    }
  });
  console.log(typeList.value);
  let obj = typeList.value.filter((v) => {
    return v.value == form.value.payType;
  });
  console.log(obj);
  form.value.payTypeName = obj[0].label;
  console.log(form.value.payTypeName);
  // 业务拆分数组
  addperformanceRef.value = [].concat(
    form.value.splitsVOList.map((v) => {
      return v.assigneeId;
    })
  );
  addperformanceRef.value.forEach((v) => {
    let performanceRate = form.value.splitsVOList.filter((v2) => {
      return v2.assigneeId == v;
    })[0];
    let item = userList.value.filter((v2) => {
      return v2.id == v;
    });
    item[0].inputValue = performanceRate.performanceRate * 100;
    addperformanceArray.value.push(item[0]);
  });
  console.log(addperformanceArray.value, "数组-1-");

  orderTime.value = formatDateTime(form.value.orderTime);
  startTime.value = formatDateTime(form.value.startTime);
  endTime.value = formatDateTime(form.value.endTime);
  //form.value.flowAdminId = form.value.flowAdminId2
  selectList.value = await getContractProductListByContractId({
    contractId: contractId.value,
  });
  console.log(selectList.value, '后去的商品');

};
// 搜索
const onSearch = () => {
  page.value = 1;
  lastPage.value = false;
  getCustomerList();
};

// 去选择产品
const selectProduct = () => {
  uni.navigateTo({
    url: "/pages/components/pages/business/selectProduct",
  });
};

const getCustomerList = async (isNextPage, pages) => {
  await getCustomerListPage({
    pageNo: page.value,
    pageSize: pageSize.value,
    relation: "my",
    name: keyword.value,
  }).then((res) => {
    if (res) {
      // 不够一页
      if (res.list.length < 10) {
        listStatus.value = "nomore";
      }
      // 最后一页
      if (res.list.length == 0) {
        lastPage.value = true;
      }
      // 第二页开始
      if (isNextPage) {
        customerList.value = customerList.value.concat(res.list);
        return;
      }
      customerList.value = res.list;

      if (form.value.customerId) {
        customerList.value.forEach((item, index) => {
          if (form.value.customerId == item.id) {
            item.checked = true;
            customerName.value = item.name;
          } else {
            item.checked = false;
          }
        });
      }
    }
  });
};
const onSearch3 = () => {
  page3.value = 1;
  userList.value = [];
  listStatus3.value = "loadmore";
  getUserList(false);
};
const getUserList = async (isNextPage, pages) => {
  await getSimpleUserList2({
    pageNo: page3.value,
    pageSize: pageSize.value,
    nickname: keyword3.value,
  }).then((res) => {
    if (res) {
      userList.value = res;
      if (form.value.orderAdminId) {
        userList.value.forEach((item, index) => {
          item.inputValue = "";
          if (form.value.orderAdminId == item.id) {
            item.checked = true;
            nickname.value = item.nickname;
          } else {
            item.checked = false;
          }
        });
      }
    }
  });
};

// 滚动到底部加载更多
const reachBottom = () => {
  if (lastPage.value || listStatus.value == "loading") return;
  listStatus.value = "loading";
  setTimeout(() => {
    getCustomerList(true, ++page.value);
    if (customerList.value.length >= 10) {
      listStatus.value = "loadmore";
    } else {
      listStatus.values = "loading";
    }
  }, 1200);
};

const reachBottom3 = () => {
  if (lastPage3.value || listStatus3.value == "loading") return;
  listStatus3.value = "loading";
  setTimeout(() => {
    getUserList(true, ++page3.value);
    if (userList.value.length >= 10) {
      listStatus3.value = "loadmore";
    } else {
      listStatus3.values = "loading";
    }
  }, 1200);
};
// 选择客户
const onItem = async (val, i) => {
  customerList.value.forEach((item, index) => {
    if (val.id == item.id) {
      item.checked = true;
      val.name = val.name ? val.name : item.name;
    } else {
      item.checked = false;
    }
  });
  form.value.customerId = val.id;
  //customerId.value = val.id
  form.value.customerName = val.name ? val.name : "";
  //选择了客户 返回客户联系人
  let data = await getContactsList({ customerId: val.id });
  customerContacts.value = data.map((v) => {
    return { ...v, checked: false };
  });

  if (data.length > 0) {
    form.value.contactsIdName = data[0].name;
    form.value.contactsId = data[0].id;
    customerContacts.value[0].checked = true;
  }
  detailAddress.value = data.length > 0 ? data[0].detailAddress : "";
  //根据客户查找商机
  // let data2 = await getBusinessPage({ customerId: val.id })
  // businessList.value = data2.list
  selectShowClose();
};

const selectShowRef2 = ref();
const selectShow2 = () => {
  unref(selectShowRef2).open();
};
const selectShowClose2 = () => {
  unref(selectShowRef2).close();
};

const onItem2 = async (val, i) => {
  customerContacts.value.forEach((item, index) => {
    if (val.id == item.id) {
      item.checked = true;
      val.name = val.name ? val.name : item.name;
    } else {
      item.checked = false;
    }
  });
  form.value.contactsId = val.id;
  //customerId.value = val.id
  form.value.contactsIdName = val.name ? val.name : "";
  selectShowClose2();
};

const selectShowRef3 = ref();
const selectShow3 = async () => {
  unref(selectShowRef3).open();
};
const selectShowClose3 = () => {
  unref(selectShowRef3).close();
};

const onItem3 = async (val, i) => {
  userList.value.forEach((item, index) => {
    if (val.id == item.id) {
      item.checked = true;
      val.nickname = val.nickname ? val.nickname : item.nickname;
    } else {
      item.checked = false;
    }
  });
  form.value.orderAdminId = val.id;
  //customerId.value = val.id
  form.value.orderAdminName = val.nickname ? val.nickname : "";
  selectShowClose3();
};

const selectShowRef4 = ref();
const selectShow4 = async () => {
  unref(selectShowRef4).open();
};
const selectShowClose4 = () => {
  unref(selectShowRef4).close();
};

const onItem4 = async (val, i) => {
  businessList.value.forEach((item, index) => {
    if (val.id == item.id) {
      item.checked = true;
      val.name = val.name ? val.name : item.name;
    } else {
      item.checked = false;
    }
  });
  form.value.businessId = val.id;
  //customerId.value = val.id
  form.value.businessName = val.name ? val.name : "";

  selectList.value = await getBusinessProductListByBusinessId({ businessId: val.id });

  selectShowClose4();
};
const selectShowRef5 = ref();
const selectShow5 = async () => {
  unref(selectShowRef5).open();
};
const selectShowClose5 = () => {
  unref(selectShowRef5).close();
};

const onItem5 = async (val, i) => {
  typeList.value.forEach((item, index) => {
    if (val.id == item.id) {
      item.checked = true;
    } else {
      item.checked = false;
    }
  });
  form.value.payType = val.value;
  form.value.payTypeName = val.label;
  selectShowClose5();
};
// 业绩拆分
const performanceRef = ref();
const addperformanceRef = ref([]);
const addperformanceArray = ref([]);
const setp = ref(1);
const openPerFormance = () => {
  unref(performanceRef).open();
};
const flagButton = () => {
  let arr = addperformanceArray.value.map((v) => {
    return v.inputValue ? Number(v.inputValue) : 0;
  });
  let number = arr.reduce((acc, curr) => acc + curr, 0);
  return !(number == 100);
};
const performanceRefClose = () => {
  unref(performanceRef).close();
};
// 设置步骤
const setpNext = (val) => {
  setp.value = val;
};
// 点击确定按钮
const serveClosePerformance = () => {
  unref(performanceRef).close();
};
const addPerformance = (item) => {
  console.log(item);
  let num = addperformanceRef.value.indexOf(item.id);
  if (num > -1) {
    addperformanceRef.value.splice(num, 1);
    addperformanceArray.value.splice(num, 1);
  } else {
    addperformanceRef.value.push(item.id);
    addperformanceArray.value.push(item);
  }
};

// 产品数量增加
const valChange = () => {
  if (form.value.status < 3) {
    count_price();
  }
};
// 优惠率改变
const inputChang = () => {
  if (form.value.status < 3) {
    count_price();
  }
};
// 移除已选产品
const remove = (i) => {
  selectList.value.splice(i, 1);
  count_price();
};
// 计算价格
const count_price = () => {
  let total = 0;
  console.log('1-1');

  setTimeout(() => {
    for (let i = 0; i < selectList.value.length; i++) {
      total += selectList.value[i].nums * selectList.value[i].price;
    }
    if (form.value.discountRate > 0) {
      total = total - (form.value.discountRate / 100) * total;
    }
    form.value.totalPrice = total.toFixed(2);
    form.value.money = total.toFixed(2);
  }, 200);
};

// 提交跟进
const uForm = ref();
const submit = (val) => {
  if (form.value.name == "") {
    uni.showToast({
      icon: "error",
      title: "请填写订单名称",
    });

    return;
  }
  if (form.value.customerId == "") {
    uni.showToast({
      icon: "error",
      title: "请选择客户",
    });

    return;
  }

  if (form.value.money == "") {
    uni.showToast({
      icon: "error",
      title: "请填写订单金额",
    });

    return;
  }

  if (form.value.contactsIdName == "") {
    uni.showToast({
      icon: "error",
      title: "请选择客户签约人",
    });

    return;
  }
  if (form.value.orderAdminIdName == "") {
    uni.showToast({
      icon: "error",
      title: "请选择公司签约人",
    });

    return;
  }

  if (selectList.value.length <= 0) {
    uni.showToast({
      icon: "error",
      title: "请选择商品",
    });

    return;
  }
  //console.log('aaaa:',(form.value.orderTime).getTime())
  onSubmit(val);
};

// 修确认提交
const onSubmit = async (val) => {
  let newArr = [];
  selectList.value.forEach((item, index) => {
    let obj = {};
    obj.name = item.storeName ? item.storeName : item.name;
    obj.nums = item.nums;
    obj.price = item.price;
    obj.productAttrUnique = item.productAttrUnique;
    obj.productId = item.productId ? item.productId : item.id;
    obj.sku = item.sku;
    obj.remarks = item.remarks;
    obj.subtotal = item.nums * item.price;
    newArr[index] = obj;
  });
  let userReqVOS = addperformanceArray.value.map((v) => {
    return {
      assigneeId: v.id,
      performanceRate: (v.inputValue / 100).toFixed(2),
      amount: ((form.value.money * v.inputValue) / 100).toFixed(2),
    };
  });
  let params = {
    orderId: "",
    amount: form.value.money,
    performanceRate: "1",
    userReqVOS: userReqVOS,
  };
  form.value.contractProducts = newArr;
  let formDate = Object.assign({}, { ...form.value, status: val });
  if (type.value == "add") {
    let res = await createContract(formDate);
    console.log(res);
    params.orderId = res;
    uni.showToast({
      title: "添加成功",
      icon: "success",
      duration: 2000,
    });
  } else {
    // selectList.value.forEach((item,index)=>{
    // 	item.subtotal = item.nums * item.price
    // })
    await updateContract(formDate);
    uni.showToast({
      title: "修改成功",
      icon: "success",
      duration: 2000,
    });
    params.orderId = form.value.id;


  }
  // 判断是否是第一次添加 就拆分了订单
  if (addperformanceArray.value.length > 0 && !form.value.splitsVOList) {
    await setSplits(params);
  }
  // 判断是不是编辑，并且调整了拆分基数
  if (
    form.value.id &&
    form.value.status < 2 &&
    addperformanceArray.value.length != form.value.splitsVOList.length
  ) {
    await setSplits(params);
  }

  prePage().$vm.isRefresh = true;
  setTimeout(() => {
    uni.navigateBack();
  }, 1000);
};
</script>

<style lang="scss" scoped>
.set-box {
  padding: 0rpx 22rpx;
  margin-bottom: 80rpx;

  .cif-title {
    padding: 22rpx 0;

    .text {
      font-size: 30rpx;
      font-weight: 700;
    }
  }

  .list {
    margin: 40rpx 15rpx 60rpx;

    .item {
      position: relative;
      border-radius: 15rpx;
      box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
      padding: 25rpx 35rpx;
      margin-bottom: 45rpx;

      .number {
        margin-bottom: 20rpx;
      }

      .content {
        margin-bottom: 20rpx;

        .price {
          width: 245rpx;
          font-size: 28rpx;
          color: #fa3534;
        }
      }

      .brief {
        margin: 10rpx 0;
        font-size: 28rpx;
        color: $uv-tips-color;
      }

      .close {
        position: absolute;
        right: -8px;
        top: -30rpx;
        background-color: #fff;
        border-radius: 50%;
        height: 60rpx;
        width: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
      }
    }
  }
}

.popup-content {
  .popup-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    font-size: 35rpx;
    font-weight: 600;
    text-align: center;
    height: 50px;
    padding-right: 25rpx;
  }

  .list {
    margin-bottom: 45rpx;

    .item {
      padding: 0 25rpx;
      justify-content: space-between;
      height: 45px;

      .title {
        flex: 1;
        font-size: 28rpx;
        font-weight: 600;
      }

      .check-icon {
        text-align: center;
        width: 100rpx;
      }
    }
  }

  .bottom_btn {
    display: flex;
    justify-content: flex-end;
    padding: 28rpx 10rpx 45rpx;
  }
}
</style>
